package com.example.springbootzklock.service;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: 加锁获取 订单号
 * @Author: mingtian
 * @CreateDate: 2019/9/24 20:33
 * @Version: 1.0
 */
public class OrderService implements Runnable {

    /**
     * 定义锁
     */
    private Lock lock = new ReentrantLock();

    private OrderNumberGenerator orderNumberGenerator = new OrderNumberGenerator();

    @Override
    public void run() {
        getNumber();
    }

    /**
     * 生成订单号  使用 分布式锁 解决
     */
    private void getNumber() {
        String number = orderNumberGenerator.getNumber();
        System.out.println(Thread.currentThread().getName() + "," + number);
    }

    /**
     * 生成订单号  使用 synchronized 解决  在本地 jvm 中有效
     */
    private synchronized void getNumberWithSync() {
        String number = orderNumberGenerator.getNumber();
        System.out.println(Thread.currentThread().getName() + "," + number);
    }

    /**
     * 生成订单号  使用 synchronized 解决  在本地 jvm 中有效
     */
    private synchronized void getNumberWithLock() {
        try {
            //加锁
            lock.lock();
            String number = orderNumberGenerator.getNumber();
            System.out.println(Thread.currentThread().getName() + "," + number);
        } catch (Exception e) {
            //释放锁
            lock.unlock();
        }
    }
}